package org.gitee.weapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.gitee.weapp.domain.common.exception.WeChatException;
import org.gitee.weapp.domain.entity.SysUser;
import org.gitee.weapp.domain.vo.LoginUser;
import org.gitee.weapp.mapper.SysUserMapper;
import org.gitee.weapp.service.LoginService;
import org.gitee.weapp.service.TokenService;
import org.gitee.weapp.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private HttpUtils httpUtils;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public String createToken(LoginUser loginUser) {
        JSONObject jsonObject = httpUtils.getCodeSession(loginUser.getCode());
        String errMsg = jsonObject.getString("errmsg");
        if (null != errMsg) {
            throw new WeChatException(errMsg);
        }
        String openId = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");

        return tokenService.createToken(openId, sessionKey, loginUser);
    }

    @Override
    public void getPhoneNumber(String code, SysUser sysUser) {
        String accessToken = httpUtils.getAccessToken(sysUser.getOpenId());
        String phoneNumber = httpUtils.getPhone(accessToken, code);
        sysUser.setPhone(phoneNumber);
        sysUserMapper.update(sysUser);
        tokenService.refreshToken(sysUser, true);
    }
}
